import type { FormInstance, FormItemProp } from "element-plus";
import { clone } from "@pureadmin/utils";
import { ref } from "vue";
import { message } from "@/utils/message";
import { sendSmsCode } from "@/api/sms";
import { REGEXP_PHONE } from "./rule";

const isDisabled = ref(false);
const timer = ref(null);
const text = ref("");

type VerifyOptions = {
  phoneField?: string;
  scene?: "bind" | "login" | "register";
  resolvePhone?: () => string | number | undefined;
};

export const useVerifyCode = (options?: VerifyOptions) => {
  const phoneField = options?.phoneField ?? "phone";
  const scene = options?.scene ?? "login";
  const start = async (
    formEl: FormInstance | undefined,
    props: FormItemProp,
    time = 60
  ) => {
    if (!formEl || isDisabled.value) return;
    const initTime = clone(time, true);
    const phoneSource = options?.resolvePhone
      ? options.resolvePhone()
      : (() => {
          const anyForm = formEl as any;
          const candidate =
            anyForm?.model ??
            anyForm?.formModel ??
            anyForm?.$props?.model ??
            {};
          return candidate?.[phoneField];
        })();

    const phone = String(phoneSource ?? "").trim();
    if (!phone) {
      message("请先填写手机号", { type: "warning" });
      try {
        await formEl.validateField(props);
      } catch {
        /* ignore */
      }
      return;
    }

    if (!REGEXP_PHONE.test(phone)) {
      message("请输入有效的 11 位手机号", { type: "warning" });
      try {
        await formEl.validateField(props);
      } catch {
        /* ignore */
      }
      return;
    }

    if (scene === "bind") {
      message("手机号绑定验证码请在绑定流程中获取", { type: "warning" });
      return;
    }

    try {
      await sendSmsCode(phone, scene === "register" ? "register" : "login");
      clearInterval(timer.value);
      isDisabled.value = true;
      text.value = `${time}`;
      if (typeof props === "string") {
        formEl.clearValidate?.([props]);
      }
      timer.value = setInterval(() => {
        if (time > 0) {
          time -= 1;
          text.value = `${time}`;
        } else {
          text.value = "";
          isDisabled.value = false;
          clearInterval(timer.value);
          time = initTime;
        }
      }, 1000);
      message("验证码已发送", { type: "success" });
    } catch (error: any) {
      clearInterval(timer.value);
      isDisabled.value = false;
      text.value = "";
      message(error?.message ?? "发送验证码失败", { type: "error" });
    }
  };

  const end = () => {
    text.value = "";
    isDisabled.value = false;
    clearInterval(timer.value);
  };

  return {
    isDisabled,
    timer,
    text,
    start,
    end
  };
};
